package com.takeshequ.chat;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.takeshequ.BasicActivity;
import com.takeshequ.Constants;
import com.takeshequ.R;

public class TalkActivity extends BasicActivity {
	private ListView listView;
	private Gson gson;

	@ViewInject(id = R.id.talk_send_msg)
	private EditText talkMsgText;
	@ViewInject(id = R.id.talk_send_btn, click = "sendMsg")
	private Button talkSendMsgBtn;
	@ViewInject(id = R.id.talk_back, click = "talkBack")
	private Button talkBack;
	@ViewInject(id = R.id.talk_expression_btn, click = "createExpressionDialog")
	private ImageView talkExpressionBtn;
	@ViewInject(id = R.id.talk_nickName)
	private TextView nickNameTextView;
	private List<TalkHistory> talkHistoryList = Collections
			.synchronizedList(new ArrayList<TalkHistory>());;
	private ItemAdapter adapter;
	private static SimpleDateFormat sf;
	private static FinalDb finadb;
	private int[] imageIds = new int[107];
	private Dialog builder;

	private Map<Integer, View> viewMap = new HashMap<Integer, View>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.talk);
		finadb = FinalDb.create(this);
		sf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
		registerMessageReceiver();
		gson = new Gson();
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

	}

	@Override
	public void onResume() {
		super.onResume();
		talkHistoryList.clear();
		listView = (ListView) findViewById(R.id.talk_listview);
		nickNameTextView.setText(Constants.firend.getNickName());
		adapter = new ItemAdapter(this.getLayoutInflater());
		listView.setAdapter(adapter);
		// talkMsgText.setFocusable(false);
		String talkGroupId = Constants.memberId + ","
				+ Constants.firend.getMemberId();
		addAndSort(finadb.findAllByWhere(TalkHistory.class, "talkGroupId = '"
				+ talkGroupId + "'" + " limit 20"));
	}

	class ItemAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private MediaPlayer mMediaPlayer = new MediaPlayer();

		private class ViewHolder {
			public TextView tvSendTime;
			public TextView tvContent;
			public TextView tvTime;
			public ImageView headImg;
		}

		public ItemAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return talkHistoryList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (talkHistoryList.size() > position) {
				View view = viewMap.get(position);
				TalkHistory talkHistory = talkHistoryList.get(position);
				final ViewHolder holder;
				if (view == null) {
					if (talkHistory.getFromId().equals(Constants.memberId)) {
						view = inflater.inflate(
								R.layout.chatting_item_msg_text_right, parent,
								false);
					} else {
						view = inflater.inflate(
								R.layout.chatting_item_msg_text_left, parent,
								false);
					}
					holder = new ViewHolder();

					holder.headImg = (ImageView) view
							.findViewById(R.id.iv_userhead);
					holder.tvSendTime = (TextView) view
							.findViewById(R.id.tv_sendtime);
					holder.tvContent = (TextView) view
							.findViewById(R.id.tv_chatcontent);
					holder.tvTime = (TextView) view.findViewById(R.id.tv_time);

					view.setTag(holder);
					viewMap.put(position, view);
				} else {
					holder = (ViewHolder) view.getTag();
				}
				if (talkHistory.getFromId().equals(Constants.memberId)) {
					FinalBitmap.create(TalkActivity.this).display(
							holder.headImg, Constants.member.getHeadImage());
				} else {
					FinalBitmap.create(TalkActivity.this).display(
							holder.headImg, Constants.firend.getHeadImage());
				}
				String content = talkHistory.getContent();
				SpannableString spannableString = ExpressionUtil
						.getExpressionString(TalkActivity.this, content);
				holder.tvContent.setText(spannableString);

				holder.tvSendTime.setText(talkHistory.getDate());

				return view;
			}
			return null;

		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(mMessageReceiver);
	}

	private MessageReceiver mMessageReceiver;

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		this.registerReceiver(mMessageReceiver, filter);
	}

	public static final String MESSAGE_RECEIVED_ACTION = "org.pushtalk.android.MESSAGE_RECEIVED_ACTION";

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
				String talkGroupId = Constants.memberId + ","
						+ Constants.firend.getMemberId();
				List<TalkHistory> talkHistoryList = finadb.findAllByWhere(
						TalkHistory.class, "talkGroupId = '" + talkGroupId
								+ "'" + " and readStatus = '0'");
				addAndSort(talkHistoryList);
			}
		}
	}

	public void sendMsg(View v) {
		String content = talkMsgText.getText().toString();
		FinalHttp httpClient = new FinalHttp();
		AjaxParams params = new AjaxParams();
		final TalkHistory talkHistory = new TalkHistory();
		if (StringUtils.isEmpty(content)) {
			Toast.makeText(this, "请输入发言内容..", 2000).show();
		} else {
			talkHistory.setContent(content);
			talkHistory.setDate(sf.format(new Date()));
			talkHistory.setTargetId(Constants.firend.getMemberId());
			talkHistory.setFromId(Constants.memberId);
			talkHistory.setTalkGroupId(Constants.memberId + ","
					+ Constants.firend.getMemberId());
			params.put("message", gson.toJson(talkHistory));
			httpClient.post(Constants.domainAndPort + "/talk/single", params,
					new AjaxCallBack<String>() {
						@Override
						public void onFailure(Throwable t, String strMsg) {
							super.onFailure(t, strMsg);
						}

						@Override
						public void onSuccess(String t) {
							JSONObject jsonObject;
							try {
								jsonObject = new JSONObject(t);
								if (jsonObject.getInt("state") == 1) {
									finadb.save(talkHistory);
									talkHistoryList.add(talkHistory);
									adapter.notifyDataSetChanged();
									talkMsgText.setText("");
									talkMsgText.clearFocus();
									InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);    
									imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
									listView.setSelection(talkHistoryList
											.size() - 1);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}
	}

	private void addAndSort(List<TalkHistory> talkHistoryListTemp) {
		for (TalkHistory talkHistory : talkHistoryListTemp) {
			talkHistoryList.add(talkHistory);
			if (talkHistory.getReadStatus().equals("0")) {
				talkHistory.setReadStatus("1");
				finadb.update(talkHistory);
			}

		}
		Collections.sort(talkHistoryList, new Comparator<TalkHistory>() {
			@Override
			public int compare(TalkHistory lhs, TalkHistory rhs) {
				return lhs.getId() - rhs.getId();
			}
		});
		adapter.notifyDataSetChanged();
		listView.setSelection(talkHistoryList.size() - 1);

	}

	public void talkBack(View v) {
		TalkActivity.this.finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
	}

	/**
	 * 创建一个表情选择对话框
	 */
	public void createExpressionDialog(View view) {
		builder = new Dialog(TalkActivity.this);
		GridView gridView = createGridView();
		builder.setContentView(gridView);
		builder.setTitle("默认表情");
		builder.show();
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bitmap bitmap = null;
				bitmap = BitmapFactory.decodeResource(getResources(),
						imageIds[arg2 % imageIds.length]);
				ImageSpan imageSpan = new ImageSpan(TalkActivity.this, bitmap);
				String str = null;
				if (arg2 < 10) {
					str = "f00" + arg2;
				} else if (arg2 < 100) {
					str = "f0" + arg2;
				} else {
					str = "f" + arg2;
				}
				SpannableString spannableString = new SpannableString(str);
				spannableString.setSpan(imageSpan, 0, 4,
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				talkMsgText.append(spannableString);
				builder.dismiss();
			}
		});
	}

	/**
	 * 生成一个表情对话框中的gridview
	 * 
	 * @return
	 */
	private GridView createGridView() {
		final GridView view = new GridView(this);
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		// 生成107个表情的id，封装
		for (int i = 0; i < 107; i++) {
			try {
				if (i < 10) {
					Field field = R.drawable.class.getDeclaredField("f00" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else if (i < 100) {
					Field field = R.drawable.class.getDeclaredField("f0" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				} else {
					Field field = R.drawable.class.getDeclaredField("f" + i);
					int resourceId = Integer.parseInt(field.get(null)
							.toString());
					imageIds[i] = resourceId;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			Map<String, Object> listItem = new HashMap<String, Object>();
			listItem.put("image", imageIds[i]);
			listItems.add(listItem);
		}

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
				R.layout.team_layout_single_expression_cell,
				new String[] { "image" }, new int[] { R.id.image });
		view.setAdapter(simpleAdapter);
		view.setNumColumns(6);
		view.setBackgroundColor(Color.rgb(214, 211, 214));
		view.setHorizontalSpacing(1);
		view.setVerticalSpacing(1);
		view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		view.setGravity(Gravity.CENTER);
		return view;
	}

}